package com.daxt.controller.webuse;

import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.daxt.common.annotations.LoginAuth;
import com.daxt.common.annotations.LoginUser;
import com.daxt.common.result.*;
import com.daxt.mapper.archives.ArticleMapper;
import com.daxt.mapper.sys.DeptMapper;
import com.daxt.mapper.use.UseBorrowRecordMapper;
import com.daxt.model.service.archives.vo.Article;
import com.daxt.model.service.base.vo.Application;
import com.daxt.model.service.base.vo.Dept;
import com.daxt.model.service.use.vo.UseBorrowRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.daxt.base.common.util.RedisUtil;
import com.daxt.base.common.util.UserInfoUtil;
import com.daxt.mapper.archives.ArchivesDocMapper;
import com.daxt.mapper.archives.ArchivesEditResearchMapper;
import com.daxt.mapper.use.UseUserRecordLogMapper;
import com.daxt.model.service.archives.result.ArchivesDocResult;
import com.daxt.model.service.archives.result.ArchivesList;
import com.daxt.model.service.archives.vo.ArchivesDoc;
import com.daxt.model.service.archives.vo.ArchivesEditResearch;
import com.daxt.model.service.base.result.UserInfo;
import com.daxt.model.service.use.vo.UseUserRecordLog;
import com.daxt.service.DocService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

@Api(tags = "档案检索(web)")
@RestController
@RequestMapping("/web")
public class SearchController {

	@Autowired
	private ArchivesDocMapper archivesDocMapper;
	@Autowired
	private UseUserRecordLogMapper useUserRecordLogMapper;
	@Autowired
	private ArchivesEditResearchMapper archivesEditResearchMapper;
	@Autowired
	private DocService docService;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private UserInfoUtil userInfoUtil;
	@Autowired
	private DeptMapper deptMapper;
	@Autowired
	private ArticleMapper articleMapper;
	@Autowired
	private UseBorrowRecordMapper useBorrowRecordMapper;



	@ApiOperation(value = "获取列表  卷/件", notes = "")
	@GetMapping("/doc")
	public Result<ArchivesList> list(@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
			@ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
			@ApiParam("门类号") @RequestParam(value = "extType", required = false) String extType,
			@ApiParam("全宗号") @RequestParam(value = "fondsId", required = false) String fondsId,
			@ApiParam("分类号") @RequestParam(value = "classNum", required = false) String classNum,
			@ApiParam("dossierId   0散文件列表  1件列表  dossierId卷下的件列表  默认1件列表") @RequestParam(value = "dossierId", required = false) String dossierId,
			@ApiParam("卷dossier 件doc") @RequestParam(value = "fileType", required = false) String fileType,
			@ApiParam("0 整理 1归档审批 2归档 3 鉴定 4销毁 5回收站") @RequestParam(value = "state", required = false) String state,
			@ApiParam("条件") @RequestParam(value = "condition", required = false) String condition,
			@ApiParam("关键词") @RequestParam(value = "keywords", required = false) String keywords,
			@ApiParam("部门")@RequestParam(value="deptId",required = false)String deptId,
			HttpServletRequest request) {
		if(StringUtils.isEmpty(dossierId)) {
			pageNum=1;
			pageSize=1000;
		}
		Result<ArchivesList> list = docService.useList(pageNum, pageSize, extType, fondsId, dossierId, condition, classNum,keywords,fileType,deptId,state,"0",null,request);
		return list;
	}


	@ApiOperation(value = "检索关键词", notes = "")
	@GetMapping("/searchKeywords")
	@LoginAuth()
	public Result<PageInfo<ArchivesDocResult>> searchKeywords(
			@ApiParam("") @RequestParam(value = "fondsId", required = false) String fondsId,
			@ApiParam("") @RequestParam(value = "typeId", required = false) String typeId,
			@ApiParam("") @RequestParam(value = "classId", required = false) String classId,
			@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
			@ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
			@ApiParam("条件") @RequestParam(value = "condition", required = false) String condition,
			@ApiParam("0件 1卷") @RequestParam(value = "model", required = false) String model,
			@ApiParam("关键词") @RequestParam(value = "keywords", required = false) String keywords,
			@ApiParam("0 收集  1归档审批  2 归档") @RequestParam(value = "state", required = false) String state,
			@ApiIgnore @LoginUser UserInfo loginUser) {

		return docService.keywordsList(pageNum, pageSize, typeId, fondsId, classId, keywords, model, state,null,loginUser,"0");
	}

	@ApiOperation(value = "检索条件", notes = "")
	@GetMapping("/searchCondition")
	public Result<PageInfo<ArchivesDocResult>> searchCondition(
			@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
			@ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
			@ApiParam("") @RequestParam(value = "extType", required = false) String extType,
			@ApiParam("") @RequestParam(value = "fondsId", required = false) String fondsId,
			@ApiParam("") @RequestParam(value = "classNum", required = false) String classNum,
			@ApiParam("条件") @RequestParam(value = "condition", required = false) String condition,
			@ApiParam("0件 1卷") @RequestParam(value = "model", required = false) String model,
			@ApiParam("0 整理  1归档审批  2 归档") @RequestParam(value = "state", required = false) String state,
			HttpServletRequest request) {
		if(!StringUtils.isEmpty(model))
			model="0".equals(model)?"doc":"dossier";

		return docService.conditionList(pageNum, pageSize, extType, fondsId, classNum, condition, model, state,request);
	}

	@ApiOperation(value = "获取档案编研", notes = "")
	@GetMapping("/editResearch/{fileId}")
	public Result<ArchivesEditResearch> editResearch(@PathVariable("fileId")Long fileId) {
		QueryWrapper<ArchivesEditResearch> queryWrapper=new QueryWrapper<ArchivesEditResearch>();
		queryWrapper.eq("docId", fileId);
		 List<ArchivesEditResearch> selectList = archivesEditResearchMapper.selectList(queryWrapper);
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", (selectList!=null&&selectList.size()>0)?selectList.get(0):null);
	}

/*	@ApiOperation(value = "检索", notes = "")
	@GetMapping("/searchFile1")
	public Result<PageInfo<DocFile>> searchFile1(@ApiParam("") @RequestParam(value = "key", required = false) String key,
			@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
			@ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
			@ApiParam("") @RequestParam(value = "extType", required = false) String extType,
			@ApiParam("") @RequestParam(value = "fondsId", required = false) String fondsId,
			@ApiParam("") @RequestParam(value = "classNum", required = false) String classNum,
			@ApiParam("条件") @RequestParam(value = "condition", required = false) String condition,
			@ApiParam("0件 1卷") @RequestParam(value = "model", required = false) String model,

		PageRequest pageable = PageRequest.of(pageNum - 1, pageSize);
		HighlightBuilder highlightBuilder = new HighlightBuilder();
		highlightBuilder.requireFieldMatch(false);
		highlightBuilder.preTags("<span style='color:red'>");
		highlightBuilder.postTags("</span>");
		highlightBuilder.field("fileKeyword");
		highlightBuilder.field("fileContent");

		NativeSearchQuery query = new NativeSearchQueryBuilder()
				.withQuery(QueryBuilders.multiMatchQuery(key, "fileKeyword", "fileContent"))
				.withHighlightFields(
						new HighlightBuilder.Field("fileKeyword").preTags("<span style='color:red'>")
								.postTags("</span>"),
						new HighlightBuilder.Field("fileContent").preTags("<span style='color:red'>")
								.postTags("</span>"))
				.withPageable(PageRequest.of(pageNum - 1, pageSize)).build();

		 SearchHits<DocFile> search = elasticsearchRestTemplate.search(query,DocFile.class);
        List<SearchHit<DocFile>> searchHits = search.getSearchHits();
        List<DocFile> discussPosts = new ArrayList<>();
        for(SearchHit<DocFile> searchHit:searchHits){
            Map<String,List<String>> highLightFields = searchHit.getHighlightFields();

            searchHit.getContent().setFileKeyword(highLightFields.get("fileKeyword") == null ? searchHit.getContent().getFileKeyword() : highLightFields.get("fileKeyword").get(0));
            searchHit.getContent().setFileContent(highLightFields.get("fileContent") == null ? searchHit.getContent().getFileContent() : highLightFields.get("fileContent").get(0));

            discussPosts.add(searchHit.getContent());
        }
       long totalHits = search.getTotalHits();
       PageInfo<DocFile> data = PageUtil.data(0L, pageNum.longValue(), totalHits, discussPosts);
       return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(),"", data);
	//	Page<DocFile> findAll = docFileRespository.search(build.getQuery(), pageable);
	//	return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", findAll);
	}
*/
	@ApiOperation(value = "利用", notes = "")
	@GetMapping("/useRecord/{fileId}/{type}")
	public Result<String> useRecord(@ApiParam("") @PathVariable("fileId") Long fileId,
			@ApiParam("0预览  1下载") @PathVariable("type") String type,
			HttpServletRequest request) {
		if(!"0".equals(type)&&!"1".equals(type)) {
			return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", "");
		}
		UserInfo loginInfo = userInfoUtil.getLoginInfo(UserInfo.class, redisUtil, request);
		ArchivesDoc doc = archivesDocMapper.selectById(fileId);
		if(doc!=null) {
			UseUserRecordLog entity=new UseUserRecordLog();
			entity.setUserId(loginInfo.getId());
			entity.setClassNum(doc.getClassNum());
			entity.setTypeNum(doc.getTypeNum());
			entity.setFondsId(doc.getFondsId());
			entity.setFileId(doc.getId());
			entity.setTitle(doc.getTitle());
			useUserRecordLogMapper.insert(entity);
		}
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), "", "");
	}


	@ApiOperation(value = "全文检索（）", notes = "")
	@GetMapping("/fullTextSearch")
	@LoginAuth()
	public Result<PageInfo<Article>> fullTextSearch(
			@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
			@ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
			@ApiParam("全宗id") @RequestParam(value = "fondsId", required = false) String fondsId,
			@ApiParam("关键词") @RequestParam(value = "keywords", required = false) String keywords,
			@ApiIgnore @LoginUser UserInfo loginUser) {

		Page<Article> page = new Page<Article>(pageNum == null ? 0 : pageNum, pageSize == null ? 10 : pageSize);
		IPage<Article> info =  articleMapper.queryArticleList(page,keywords,fondsId);



		info.getRecords().forEach((Article ar)->{
			if(!StringUtils.isEmpty(ar.getFileName())){
				List<String> fList = Arrays.asList(ar.getFileName().split(","));
				ar.setFileNames(fList);
			}

			ArchivesDoc aDoc = archivesDocMapper.selectById(ar.getId());
			if(null != aDoc){
				ar.setFileType(aDoc.getFileType());
				ar.setArchivalNum(aDoc.getArchivalNum());
				ar.setDutyPeople(aDoc.getDutyPeople());
			}


			if(!StringUtils.isEmpty(ar.getContent()) && ar.getContent().indexOf(keywords) >0){
				String oo = ar.getContent().substring(0,ar.getContent().indexOf(keywords));// \r

				int o = 0;
				if(oo.lastIndexOf("\r")>0){
					o = oo.lastIndexOf("\r") + 1;
				}


				String restr = "";
				String ao = ar.getContent().substring(o);
				if(ao.indexOf("\r") > 0){
					restr = ao.substring(0,ao.indexOf("\r"));
				}else{
					restr = ar.getContent().substring(o);
				}

				ar.setContentStr(restr);
//				ar.setContentStr(ar.getContent().substring(ar.getContent().indexOf(keywords),ar.getContent().indexOf(keywords) + 10));
			}


			QueryWrapper<UseBorrowRecord> uQw = new QueryWrapper();
			uQw.eq("userId",loginUser.getId());
			uQw.eq("fileId",ar.getId());
			UseBorrowRecord ubr = useBorrowRecordMapper.selectOne(uQw);
			if(null != ubr)ar.setBorrowState(ubr.getState());

		});


//		List<Article> infoList =  articleMapper.queryList(keywords);
		PageInfo<Article> data = PageUtil.data(info.getPages(), info.getCurrent(), info.getTotal(), info.getRecords());

		return ResultUtil.success(data);

	}


}
